<script setup lang="ts">
import ReCol from "@/components/ReCol";
import { ref, reactive, watch, computed } from "vue";
import { ElTable, ElTableColumn, ElInputNumber, ElInput, ElMessageBox } from "element-plus";
import { message } from "@/utils/message";

interface BatchFormProps {
  formInline: {
    user_id?: number;
    userList: Array<{ id: number; name: string }>;
    accountList: Array<{ id: number; wa_account: string; admin_user_id?: number; remark?: string; status?: number }>;
    remark?: string;
  };
}

const props = withDefaults(defineProps<BatchFormProps>(), {
  formInline: () => ({
    user_id: undefined,
    userList: [],
    accountList: [],
    remark: ""
  })
});

const ruleFormRef = ref();
const newFormInline = ref(props.formInline);
const applications = ref<Array<{ account_id: number; amount: number; enabled: boolean }>>([]);

function getRef() {
  return ruleFormRef.value;
}

// 计算属性：根据选择的用户筛选账号
const userAccounts = computed(() => {
  if (!newFormInline.value.user_id) {
    return [];
  }
  return newFormInline.value.accountList.filter(
    account => account.admin_user_id === newFormInline.value.user_id
  );
});

// 计算属性：获取选中的用户信息
const selectedUser = computed(() => {
  if (!newFormInline.value.user_id) {
    return null;
  }
  const user = newFormInline.value.userList.find(
    user => user.id === newFormInline.value.user_id
  );
  return user ? { id: user.id, username: user.name } : null;
});

// 监听用户选择变化，重置申请数据
watch(() => newFormInline.value.user_id, (newUserId) => {
  if (newUserId && userAccounts.value.length > 0) {
    // 初始化申请数据
    applications.value = userAccounts.value.map(account => ({
      account_id: account.id,
      amount: 0,
      enabled: false
    }));
  } else {
    applications.value = [];
  }
});

// 监听账号列表变化，同步更新申请数据
watch(userAccounts, (newAccounts) => {
  if (newAccounts.length > 0) {
    applications.value = newAccounts.map(account => ({
      account_id: account.id,
      amount: 0,
      enabled: false
    }));
  } else {
    applications.value = [];
  }
});

// 获取表单数据用于提交
const getFormData = () => {
  const enabledApplications = applications.value.filter(app => app.enabled && app.amount > 0);
  
  if (!newFormInline.value.user_id) {
    throw new Error("请选择账号使用者");
  }
  
  if (enabledApplications.length === 0) {
    throw new Error("请至少选择一个账号并填写充值金额");
  }

  return {
    user_id: newFormInline.value.user_id,
    applications: enabledApplications.map(app => ({
      account_id: app.account_id,
      amount: app.amount
    })),
    remark: newFormInline.value.remark || ""
  };
};

// 切换全选
const toggleSelectAll = (checked: boolean) => {
  applications.value.forEach((app, index) => {
    // 只选择正常状态的账号
    if (userAccounts.value[index]?.status == 1) {
      app.enabled = checked;
      if (!checked) {
        app.amount = 0;
      }
    }
  });
};

// 批量设置金额
const batchSetAmount = () => {
  ElMessageBox.prompt('请输入要批量设置的充值金额', '批量设置金额', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    inputPattern: /^\d+(\.\d{1,2})?$/,
    inputErrorMessage: '请输入有效的金额（最多两位小数）'
  }).then(({ value }) => {
    const amount = parseFloat(value);
    if (amount > 0 && amount <= 99999.99) {
      applications.value.forEach(app => {
        if (app.enabled) {
          app.amount = amount;
        }
      });
      message("批量设置金额成功", { type: "success" });
    } else {
      message("金额必须在0.01-99999.99之间", { type: "error" });
    }
  }).catch(() => {
    // 用户取消
  });
};

defineExpose({ getRef, getFormData });

const formRules = {
  user_id: [
    { required: true, message: "请选择账号使用者", trigger: "change" }
  ]
};
</script>

<template>
  <el-form
    ref="ruleFormRef"
    :model="newFormInline"
    :rules="formRules"
    label-width="130px"
  >
    <el-row :gutter="30">
      <re-col :value="24" :xs="24" :sm="24">
        <el-form-item label="账号使用者" prop="user_id">
          <el-select
            v-model="newFormInline.user_id"
            placeholder="请选择账号使用者"
            clearable
            filterable
            style="width: 100%"
          >
            <el-option
              v-for="user in newFormInline.userList"
              :key="user.id"
              :label="user.name"
              :value="user.id"
            />
          </el-select>
        </el-form-item>
      </re-col>

      <re-col :value="24" :xs="24" :sm="24">
        <el-form-item label="申请备注">
          <el-input
            v-model="newFormInline.remark"
            :rows="2"
            type="textarea"
            placeholder="请输入批量申请的备注信息"
            style="width: 100%"
          />
        </el-form-item>
      </re-col>

      <!-- 账号列表表格 -->
      <re-col :value="24" :xs="24" :sm="24" v-if="userAccounts.length > 0">
        <el-form-item label="账号充值列表">
          <div style="width: 100%">
            <div style="margin-bottom: 12px; display: flex; gap: 12px; align-items: center;">
              <el-checkbox 
                :indeterminate="applications.some((app, index) => app.enabled && userAccounts[index]?.status !== 0) && !applications.every((app, index) => app.enabled || userAccounts[index]?.status === 0)"
                :model-value="applications.length > 0 && applications.every((app, index) => app.enabled || userAccounts[index]?.status === 0)"
                @change="toggleSelectAll"
              >
                全选
              </el-checkbox>
              <el-button 
                type="primary" 
                size="small" 
                @click="batchSetAmount"
                :disabled="!applications.some(app => app.enabled)"
              >
                批量设置金额
              </el-button>
              <span style="color: #909399; font-size: 14px;">
                已选择 {{ applications.filter(app => app.enabled).length }} 个账号
              </span>
            </div>
            
            <el-table 
              :data="userAccounts" 
              border 
              style="width: 100%" 
              max-height="400"
            >
              
              
              <el-table-column label="选择" width="60">
                <template #default="{ row, $index }">
                  <el-tooltip
                    v-if="row.status === 0"
                    content="该账号已停用，无法选择"
                    placement="top"
                  >
                    <el-checkbox 
                      v-model="applications[$index].enabled"
                      disabled
                    />
                  </el-tooltip>
                  <el-checkbox 
                    v-else
                    v-model="applications[$index].enabled"
                    @change="(checked) => !checked && (applications[$index].amount = 0)"
                  />
                </template>
              </el-table-column>
              <el-table-column type="index" label="序号" width="60" />
              <el-table-column prop="wa_account" label="WhatsApp账号" min-width="150">
                <template #default="{ row }">
                  <div>
                    <div style="display: flex; align-items: center; gap: 8px;">
                      <span>{{ row.label }}</span>
                      <el-tag v-if="row.status === 0" type="danger" size="small">已停用</el-tag>
                    </div>
                    <div v-if="row.remark" style="color: #909399; font-size: 12px;">
                      {{ row.remark }}
                    </div>
                  </div>
                </template>
              </el-table-column>
              
              <el-table-column label="充值金额" width="200">
                <template #default="{ row, $index }">
                  <el-input-number
                    v-model="applications[$index].amount"
                    :min="0"
                    :max="99999.99"
                    :step="0.01"
                    :precision="2"
                    placeholder="0.00"
                    style="width: 100%"
                    :disabled="!applications[$index].enabled || row.status === 0"
                    @focus="!applications[$index].enabled && row.status !== 0 && (applications[$index].enabled = true)"
                  />
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-form-item>
      </re-col>

      <!-- 用户信息显示 -->
      <re-col :value="24" :xs="24" :sm="24" v-if="selectedUser && userAccounts.length === 0">
        <el-form-item>
          <el-alert
            :title="`用户 ${selectedUser.username} 暂无可用的WhatsApp账号`"
            type="info"
            show-icon
            :closable="false"
          />
        </el-form-item>
      </re-col>
    </el-row>
  </el-form>
</template>

<style scoped>
:deep(.el-table .el-table__cell) {
  padding: 8px 0;
}

:deep(.el-input-number .el-input__inner) {
  text-align: left;
}
</style> 